import 'package:flutter/material.dart';
import 'package:task_manager/core/constants/enums.dart';
import 'package:task_manager/model/list/list_item_model.dart';

class ListProvider with ChangeNotifier {
  TaskPeriod taskPeriod;

  List<ListItemModel> _items = [
    ListItemModel(
        id: 0,
        title: '首个待办项',
        description: '这里填待办项描述',
        period: TaskPeriod.DAILY,
        status: TaskStatus.DONE),
    ListItemModel(
        id: 1,
        title: '第二个待办项',
        description: '这里填待办项描述',
        period: TaskPeriod.WEEKLY,
        status: TaskStatus.DONE),
    ListItemModel(
        id: 2,
        title: '第三个待办项',
        description: '这里填待办项描述',
        period: TaskPeriod.MONTHLY,
        status: TaskStatus.TODO),
  ];

  List<ListItemModel> get items {
    _items ??= <ListItemModel>[];
    if (taskPeriod == null) return _items.reversed.toList();
    return _items
            ?.where((element) => element.period == taskPeriod)
            ?.toList()
            ?.reversed
            ?.toList() ??
        <ListItemModel>[];
  }

  int get itemsLength => items?.length ?? 0;
  int get lastItemId {
    if (itemsLength == 0) return itemsLength;
    return _items?.last?.id ?? 0;
  }

  set setPeriod(TaskPeriod period) {
    if (period == taskPeriod) return;
    taskPeriod = period;
    notifyListeners();
  }

  void addItem(ListItemModel item) {
    item
      ..id = lastItemId == 0 ? 0 : lastItemId + 1
      ..status = TaskStatus.TODO;
    _items.add(item);
    notifyListeners();
  }

  void editItem(ListItemModel item) {
    int index = _items.indexOf(
        _items.where((element) => element.id == item.id).toList().first);
    if (index == -1) return;
    _items[index] = item;
    notifyListeners();
  }

  void markAsDone(int id) {
    var item = _items.where((element) => element.id == id).toList().first;
    item.status = TaskStatus.DONE;
    notifyListeners();
  }

  void removeItem(int id) {
    if (_items?.elementAt(id) == null) return;
    _items.removeAt(id);
    notifyListeners();
  }
}
